package com.gcloud.mesh.dcs.service;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.entity.IaasEntity;
import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.dao.SchedulerImagineDao;
import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.entity.AppEntity;
import com.gcloud.mesh.dcs.entity.SchedulerAdviceEntity;
import com.gcloud.mesh.dcs.entity.SchedulerImagineEntity;
import com.gcloud.mesh.dcs.entity.SchedulerJobEntity;
import com.gcloud.mesh.dcs.enums.SchedulerModelDict;
import com.gcloud.mesh.header.enums.ModelType;
import com.gcloud.mesh.header.vo.dcs.AppNodExpand;
import com.gcloud.mesh.monitor.service.StatisticsService;
import com.gcloud.mesh.supplier.adapter.AliPowerConsumptionAdapter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class MigrateScheduleResultHandler {
	@Autowired
	private AppDao appDao;
	@Autowired
	private SchedulerAdviceService schedulerAdviceService;
	@Autowired
	private SchedulerImagineDao schedulerImagineDao;
	@Autowired
	private StatisticsService statisticsService;

	@Autowired
	private SysDictMapper sysDictMapper;

	@Autowired
	private SchedulerJobDao schedulerJobDao;
	@Autowired
	private ModelService modelService;
	@Autowired
	private IaasDao IaasDao;
	@Autowired
	private AliPowerConsumptionAdapter aliPowerConsumptionAdapter;

	public void handleMigrate(String jobId) {
		// 更新app的resouceId
		SchedulerJobEntity job = schedulerJobDao.getById(jobId);
		String appId = job.getAppId();
		String destCloudResourceId = job.getDstCloudResourceId();
		Integer schedulerModel = job.getSchedulerModel();
		String destDatacenterId = job.getDstDatacenterId();
		AppEntity app = appDao.getById(appId);
		List<SchedulerAdviceEntity> adviceInstances = schedulerAdviceService.listByAppId(appId);
		if (adviceInstances == null || adviceInstances.isEmpty()) {
			appDao.updateAppResourceIdAndDataCenterId(appId, destCloudResourceId);
			releaseNodes(job.getSrcDatacenterId(), app);
		}
		if (schedulerModel != null) {
			ModelType modelType = ModelType.get(SchedulerModelDict.get(String.valueOf(schedulerModel)).name());
			SchedulerImagineEntity entity = schedulerImagineDao.get(modelType, appId, job.getSrcDatacenterId(),
					destDatacenterId, SchedulerImagineEntity.class);

			StringBuilder values = new StringBuilder();

			String factorTypes = entity.getFactorTypes();
			String[] meters = factorTypes.split(",");
			for (String meter : meters) {
				String valueStr = statisticsService.latestSample(meter, job.getSrcDatacenterId());
				Double value = Double.parseDouble(valueStr);
				BigDecimal valueb = new BigDecimal(value);
				value = valueb.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				
				if (values.length() > 0) {
					values.append(",");
				}
				values.append(value);
			}

			if (entity != null) {
				schedulerImagineDao.updateAfter(entity, values.toString());
			}

//			SchedulerImagineEntity schedulerImagineEntity = new SchedulerImagineEntity();
//			schedulerImagineEntity.setId(UUID.randomUUID().toString());
//			schedulerImagineEntity.setAppId(app.getId());
//			schedulerImagineEntity.setSourceNodeId(null);
//			schedulerImagineEntity.setDestNodeId(null);
//			schedulerImagineEntity.setModelType(modelType.name());
//			schedulerImagineEntity.setUpdateTime(new Date());
//			schedulerImagineDao.save(schedulerImagineEntity);

			// 增加迁移成功后更新数据中心模型，把最优模型设到用户模型
			if (job.getSchedulerModel() != null) {
				if (job.getSchedulerModel().equals(0)) {
					modelService.updateBestPredictAndHistory(ModelType.DATACENTER_COST.name());
				} else {
					modelService.updateBestPredictAndHistory(ModelType.DATACENTER_DEVICE.name());
				}

			}
		}

	}

	/**
	 * 释放资源，目前是整个数据中心释放
	 * 
	 * @param srcDatacenterId
	 */
	private void releaseNodes(String srcDatacenterId, AppEntity appEntity) {
		// 迁移成功判断数据中心是否还有应用，释放资源
		log.info("开始调用阿里的功耗平台释放资源");
		try {
			// 如果应用的扩展字段有服务器信息
			if (appEntity != null && appEntity.getNodeExpand() != null) {
				List<AppNodExpand> expands = JSONObject.parseArray(appEntity.getNodeExpand(), AppNodExpand.class);
				for (AppNodExpand expand : expands) {
					IaasEntity en = IaasDao.getById(expand.getNodeId());
					aliPowerConsumptionAdapter.releaseDevice(en.getEsn());
				}
			} else {
				// 释放数据中心所有的服务器
				int count = appDao.countDatacenterApp(srcDatacenterId);
				if (count == 0) {
					// 释放数据中心所有服务器
					List<IaasEntity> iaass = IaasDao.findNodeByDatacenterId(srcDatacenterId);
					for (IaasEntity iaas : iaass) {
						aliPowerConsumptionAdapter.releaseDevice(iaas.getEsn());
					}
				}
			}

		} catch (Exception e) {
			log.error("开始调用阿里的功耗平台释放资源报错：", e);
			e.printStackTrace();
		}
	}
}
